package com.bbx.taxi.client.Activity.Order;

import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentLinkedQueue;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.View.OnTouchListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;
import butterknife.InjectView;

import com.bbx.androidapi.util.ToastUtil;
import com.bbx.api.gclient.GMsg;
import com.bbx.api.sdk.model.official.passanger.Return.OrderList.OfficialOrderList;
import com.bbx.api.sdk.model.passanger.OrderDetailBuild;
import com.bbx.api.sdk.model.passanger.OrderEvaluate;
import com.bbx.api.sdk.model.passanger.Return.OrderDetails;
import com.bbx.api.sdk.model.passanger.Return.Jmsg.Msgs;
import com.bbx.api.sdk.net.base.JsonBuild;
import com.bbx.api.sdk.net.passeger.conn.CodeNet;
import com.bbx.api.sdk.net.passeger.conn.OrderDetailNet;
import com.bbx.api.sdk.net.passeger.conn.OrderEvaluateNet;
import com.bbx.taxi.client.Task.BaseAsyncTask;
import com.bbx.taxi.client.MyApplication;
import com.bbx.taxi.official.R;
import com.bbx.taxi.client.Activity.MainActivity;
import com.bbx.taxi.client.Activity.Base.BaseBBXActivity;
import com.bbx.taxi.client.Activity.login.LoginActivity.CodeTask;
import com.bbx.taxi.client.Bean.Value;
import com.bbx.taxi.client.Bean.Attribute.MainAttribute;
import com.bbx.taxi.client.Bean.Extra.MainMsg;
import com.bbx.taxi.client.Bean.Extra.OrderMsg;
import com.bbx.taxi.client.DB.MyOrder.MyOrderDB;
import com.bbx.taxi.client.DB.MyOrder.MyOrderingDB;
import com.bbx.taxi.client.Util.DateFormat;
import com.bbx.taxi.client.Util.FormatUtil;
import com.bbx.taxi.client.emoji.MyConvertToMsg;
import com.bbx.taxi.client.widget.MaxByteLengthEditText;
import com.bbx.taxi.client.widget.SlidingCard.DiscoverContainerView;
import com.bbx.taxi.client.widget.SlidingCard.DiscoverContainerView.OnFinish;
import com.bbx.taxi.client.widget.SlidingCard.OrderVo;

/**
 * 订单评价
 * 
 */
public class OrderEvaluationActivity extends BaseBBXActivity {
	@InjectView(R.id.contentview)
	DiscoverContainerView contentView;
	/** 司机名称 */
	@InjectView(R.id.tv_drivername)
	TextView tv_drivername;
	/** 车牌号 */
	@InjectView(R.id.tv_car_no)
	TextView tv_car_no;
	/** 时间 */
	@InjectView(R.id.tv_time)
	TextView tv_time;
	/** 订单类型 */
	@InjectView(R.id.order_type)
	TextView tv_order_type;
	/** 人数 */
	@InjectView(R.id.tv_count)
	TextView tv_count;
	/** 出发地 */
	@InjectView(R.id.tv_start)
	TextView tv_start;
	/** 目的地 */
	@InjectView(R.id.tv_end)
	TextView tv_end;
	/** 金额 */
	@InjectView(R.id.tv_money)
	TextView tv_money;
	/** 优惠价折扣 */
	@InjectView(R.id.tv_coupon)
	TextView tv_coupon;
	/** 内容 */
	@InjectView(R.id.layout_message)
	LinearLayout layout_message;
	/** 提示语 */
	@InjectView(R.id.hint)
	TextView hint;
	@InjectView(R.id.et_message)
	MaxByteLengthEditText et_message;
	@InjectView(R.id.et_message2)
	TextView et_message2;
	@InjectView(R.id.hint_line)
	View hint_line;
	/** 再次下单 */
	@InjectView(R.id.btn_confirm)
	Button btn_confirm;
	/** 评价 */
	@InjectView(R.id.rb_rating_s)
	RatingBar rb_rating_s;
	@InjectView(R.id.tv_rating)
	TextView tv_rating;
	@InjectView(R.id.rb_rating_b)
	RatingBar rb_rating_b;
	@InjectView(R.id.myscrollview)
	ScrollView myscrollview;
	@InjectView(R.id.layout_coupon)LinearLayout layout_coupon;
	@InjectView(R.id.layout_money)LinearLayout layout_money;
	ConcurrentLinkedQueue<OfficialOrderList> dataList = new ConcurrentLinkedQueue<OfficialOrderList>();
	private int order_type;
	private int viewId;
	/** 订单Id集合 */
	private List<String> lits_order_id = new ArrayList<String>();
	public String coupon;
	/** 最下面的那个页面的，主要用于传递到卡片上去。卡片根据状态显示样本。评价状态，0待评价，1正在评价，2已评价 */
	public int status = 0;
	private OfficialOrderList mOfficialOrderList;
	private MyOrderDB db_myorder;// 我的订单数据库
	private OrderEvaluateTask mOrderEvaluateTask;
	private OrderDetailTask mOrderDetailTask;
	private boolean isonNotify = false;
	private boolean isTouch = true;
	private String order_id;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		setContentView(R.layout.activity_orderevaluation);
		super.onCreate(savedInstanceState);
		

	}

	@Override
	protected void initView() {
		setTitle(getString(R.string.order_detail));
		et_message.setOnEditorActionListener(new OnEditorActionListener() {	
			@Override
			public boolean onEditorAction(TextView arg0, int arg1, KeyEvent event) {
				return (event.getKeyCode() == KeyEvent.KEYCODE_ENTER);
			}
		});
		et_message.setMaxByteLength(60);
		et_message.setOnClickListener(this);
		et_message.setOnFocusChangeListener(new OnFocusChangeListener() {
			@Override
			public void onFocusChange(View arg0, boolean arg1) {
				if(arg1){
				new Handler().postDelayed(new  Runnable() {
					public void run() {
						myscrollview.fullScroll(ScrollView.FOCUS_DOWN);
					}
				},800);
				}
			}
		});
		isonNotify = true;
		db_myorder = new MyOrderDB(this);
		Intent intent = getIntent();
		final String order_id = intent.getExtras().getString(
				OrderMsg.order_id_finish);
		this.order_id = order_id;
		mOfficialOrderList = db_myorder.onReadDB(context, order_id);
		if (Integer.parseInt(mOfficialOrderList.getValuate_status())==(Value.VALUATE_STATUS)) {// 如果该订单已完成，则显示完成界面
			// 已评价
			status =Value.VALUATE_STATUS;
			layout_message.setVisibility(View.VISIBLE);
			et_message.setVisibility(View.GONE);
			hint.setVisibility(View.GONE);
			hint_line.setVisibility(View.GONE);
			et_message2.setVisibility(View.VISIBLE);
			et_message2.setText(et_message.getText().toString());
			btn_confirm.setText(R.string.agin_xiadan);
			rb_rating_b.setIsIndicator(true);
			isTouch = false;
			rb_rating_b.setRating(FormatUtil.onFormatStar((float) mOfficialOrderList.getDriver_star()));
		}
		if (order_id == null || order_id.equals(""))
			finish();
		getOrderDetail(order_id,true);
		lits_order_id.add(order_id);
		tv_drivername.setText(mOfficialOrderList.getDriver_name());
		tv_car_no.setText(mOfficialOrderList.getCar_NO());
		tv_time.setText(DateFormat.onDateRemove_ss(mOfficialOrderList.getAppoint_time()));
		order_type = Integer.parseInt(mOfficialOrderList.getOrder_type() );
		switch (order_type) {
		case Value.ORDER_TYPE_SN:
			tv_order_type.setText(R.string.sn);
			viewId = Value.VIEWID_SN;
			tv_count.setVisibility(View.GONE);
			layout_money.setVisibility(View.GONE);
			break;
		case Value.ORDER_TYPE_KJ:
			tv_order_type.setText(R.string.kj);
			viewId = Value.VIEWID_KJ;
//			tv_count.setText(String.format(getString(R.string.num_jian), mOfficialOrderList.getOrderDetail().getCount()));
			break;
		case Value.ORDER_TYPE_PC:
			tv_order_type.setText(R.string.pc);
//			tv_count.setText(String.format(getString(R.string.num), mOfficialOrderList.getOrderDetail().getCount()));
			viewId = Value.VIEWID_PC;
			break;
		case Value.ORDER_TYPE_BC:
			tv_order_type.setText(R.string.bc);
//			tv_count.setText(String.format(getString(R.string.num_car), mOfficialOrderList.getOrderDetail().getCount()));
			viewId = Value.VIEWID_BC;
			break;
		}

		tv_start.setText(mOfficialOrderList.getOrderDetail().getStart().getAddress());
		tv_end.setText(mOfficialOrderList.getOrderDetail().getEnd().getAddress());
		rb_rating_s.setRating(FormatUtil.onFormatStar((float) mOfficialOrderList.getDriver_star()));
		tv_rating.setText(FormatUtil.onFormatStar((float) mOfficialOrderList.getDriver_star())+"");
		if (dataList.size() > 0) {
			contentView.setVisibility(View.VISIBLE);
			setOnCloseSwipeLayout(true);
		} else {
			setOnCloseSwipeLayout(false);
		}
		contentView.initCardView(OrderEvaluationActivity.this, dataList);
		contentView.setOnFinish(new OnFinish() {

			@Override
			public void onFinish() {
				setOnCloseSwipeLayout(false);

			}
		});
		btn_confirm.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (btn_confirm.getText().toString().equals(context.getString(R.string.submit_evaluation))) {
					// 提交评价
					OrderEvaluate mOrderEvaluate = new OrderEvaluate(context);
					mOrderEvaluate.uid = mApplication.getUid();
					mOrderEvaluate.access_token = mApplication.getToken();
					mOrderEvaluate.order_id = order_id;
					mOrderEvaluate.driver_id = mOfficialOrderList.driver_id;
					mOrderEvaluate.star = ((int) rb_rating_b.getRating())*20;
					mOrderEvaluate.suggest = new MyConvertToMsg().parseEmoji(context,et_message.getText().toString());
					mOrderEvaluate.problem = "";
					mOrderEvaluateTask = new OrderEvaluateTask(context,
							mOrderEvaluate);
					mOrderEvaluateTask.execute();
				} else {
					MainAttribute main = MainAttribute.getInstance();
					main.setAttribute(context,mOfficialOrderList);

					Intent intent = new Intent();
					intent.setClass(OrderEvaluationActivity.this,
							MainActivity.class);
					intent.putExtra(MainMsg.extra_viewpageId, viewId);
					intent.putExtra(MainMsg.extra_agin_xiadan, MainMsg.AGAIB_XIADAN);
					intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); // 注意本行的FLAG设置
					startActivity(intent);
				}
			}
		});
		rb_rating_b.setIsIndicator(true);
		rb_rating_b.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if (!isTouch)
					return true;
				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
					// 正在评价
					status = 1;
					layout_message.setVisibility(View.GONE);
					et_message.setVisibility(View.VISIBLE);
					btn_confirm.setText(R.string.submit_evaluation);
					new Handler().postAtTime(new Runnable() {
						@Override
						public void run() {
							rb_rating_b.setIsIndicator(false);
						}
					}, 200);
					break;
				}
				return false;
			}
		});
	}

	@Override
	protected void initData() {

	}

	private void addCardView(String order_id) {
		this.order_id = order_id;
		// 如果contentView数据为空，则add为加旧的，另外一个布局加新的，
		if (contentView.getVisibility() == View.GONE) {
			contentView.setVisibility(View.VISIBLE);
		}
		setOnCloseSwipeLayout(true);
		onScrollOrigin();
		if (mOfficialOrderList != null)
			dataList.add(mOfficialOrderList);

		// 加新的数据
		// mMyOrderList赋值要在添加卡片后面
		mOfficialOrderList = db_myorder.onReadDB(context, order_id);
		getOrderDetail(order_id,false);
		lits_order_id.add(order_id);
		tv_drivername.setText(mOfficialOrderList.getDriver_name());
		tv_time.setText(DateFormat.onDateRemove_ss(mOfficialOrderList.getAppoint_time()));
		order_type = Integer.parseInt(mOfficialOrderList.getOrder_type());
		layout_money.setVisibility(View.VISIBLE);
		switch (order_type) {
		case Value.ORDER_TYPE_SN:
			tv_order_type.setText(R.string.sn);
			tv_count.setVisibility(View.GONE);
			layout_money.setVisibility(View.GONE);
			break;
		case Value.ORDER_TYPE_PC:
			tv_order_type.setText(R.string.pc);
//			tv_count.setText(String.format(getString(R.string.num), mOfficialOrderList.getOrderDetail().getCount()));
			break;
		case Value.ORDER_TYPE_BC:
			tv_order_type.setText(R.string.bc);
//			tv_count.setText(String.format(getString(R.string.num_car), mOfficialOrderList.getOrderDetail().getCount()));
			break;
		case Value.ORDER_TYPE_KJ:
			tv_order_type.setText(R.string.kj);
//			tv_count.setText(String.format(getString(R.string.num_jian), mOfficialOrderList.getOrderDetail().getCount()));
			break;
		}
		tv_start.setText(mOfficialOrderList.getOrderDetail().getStart().getAddress());
		tv_end.setText(mOfficialOrderList.getOrderDetail().getEnd().getAddress());
		tv_money.setText(String.format(getString(R.string.price), "?"));
		tv_coupon.setText(String.format(getString(R.string.price), "?"));
		rb_rating_s.setRating(FormatUtil.onFormatStar((float) mOfficialOrderList.getDriver_star()));
		tv_rating.setText(FormatUtil.onFormatStar((float) mOfficialOrderList.getDriver_star())+"");
		contentView.initCardView(OrderEvaluationActivity.this, dataList);
		onRecovery();
	}

	/**
	 * 恢复界面原来的样子
	 */
	public void onRecovery() {
		status = 0;
		layout_message.setVisibility(View.VISIBLE);
		et_message.setVisibility(View.GONE);
		et_message2.setVisibility(View.GONE);
		hint.setVisibility(View.VISIBLE);
		hint_line.setVisibility(View.VISIBLE);
		btn_confirm.setText(R.string.agin_xiadan);
		rb_rating_b.setIsIndicator(false);
		rb_rating_b.setRating(0);
	}

	/**
	 * 获取订单详情
	 */
	public void getOrderDetail(String order_id,boolean isLoading) {
		OrderDetailBuild mOrderDetail = new OrderDetailBuild(context);
		mOrderDetail.uid = mApplication.getUid();
		mOrderDetail.access_token = mApplication.getToken();
		mOrderDetail.order_id = order_id;
		mOrderDetailTask = new OrderDetailTask(context, mOrderDetail,isLoading);
		mOrderDetailTask.execute();
	}

	/**
	 * 订单详情
	 */
	private class OrderDetailTask extends BaseAsyncTask {

		private OrderDetailBuild mOrderDetail;

		public OrderDetailTask(Activity context, OrderDetailBuild mOrderDetail,boolean isLoading) {
			super(context,isLoading);
			this.mOrderDetail = mOrderDetail;
		}

		@Override
		public void onSuccess(Object object) {
			if (object != null) {
//				OrderDetails mOrderDetails = (OrderDetails) object;
//				if(mOrderDetails!=null){
//					tv_money.setText(String.format(getString(R.string.price), FormatUtil.onFormatPrice(mOrderDetails.getDetails().getPrice())));
//					if(mOrderDetails.getDetails().getDiscount()!=null){
//					tv_coupon.setText(String.format(getString(R.string.price),mOrderDetails.getDetails().getDiscount().getSum()));
//					}
//					if(mOrderDetails.getDetails().getStar()!=null){
//					rb_rating_s.setRating(FormatUtil.onFormatStar((float)mOrderDetails.getDetails().getDriver_star()));
//					tv_rating.setText(FormatUtil.onFormatStar((float)mOrderDetails.getDetails().getDriver_star())+"");	
//					}
//					if(mOrderDetails.getDetails().getCar_No()!=null)
//					tv_car_no.setText(mOrderDetails.getDetails().getCar_No());
//					if(et_message2.getText().toString().equals(""))
//					et_message2.setText(mOrderDetails.getDetails().getSuggest());
//					
//					if (Integer.parseInt(mOfficialOrderList.getValuate_status())==(Value.VALUATE_STATUS)) {// 如果该订单已完成，则显示完成界面
//						if(mOrderDetails.getDetails().getStar()!=null)
//						rb_rating_b.setRating(FormatUtil.onFormatStar(Float.parseFloat(mOrderDetails.getDetails().getStar())));				
//					}
//					//设置值
//					mOfficialOrderList.setPrice(mOrderDetails.getDetails().getPrice());
//					mOfficialOrderList.setDriver_star((float)mOrderDetails.getDetails().getDriver_star());
//					mOfficialOrderList.setSuggest(mOrderDetails.getDetails().getSuggest());
//					if(mOrderDetails.getDetails().getStar()!=null){
//					mOfficialOrderList.setStar(Float.parseFloat(mOrderDetails.getDetails().getStar()));
//					}
//					if(mOrderDetails.getDetails().getDiscount()!=null){
//					  layout_coupon.setVisibility(View.VISIBLE);
//					   mOfficialOrderList.setCoupon_sum(mOrderDetails.getDetails().getDiscount().getSum());
//					}
//				}

			} else {
				ToastUtil.showToast(context,R.string.no_network);
			}
		}

		@Override
		public void onFailed(int status, String msg) {
			ToastUtil.showToast(context,R.string.no_network);
		}

		@Override
		protected Object doInBackground(Object... params) {
			// TODO Auto-generated method stub
			String json = new JsonBuild().setModel(mOrderDetail).getJson();
			return new OrderDetailNet(context, json);
		}
	}

	/**
	 * 订单评价
	 * 
	 */
	public class OrderEvaluateTask extends BaseAsyncTask {

		private OrderEvaluate mOrderEvaluate;

		public OrderEvaluateTask(Activity context, OrderEvaluate mOrderEvaluate) {
			super(context);
			this.mOrderEvaluate = mOrderEvaluate;
		}

		@Override
		protected Object doInBackground(Object... params) {
			// TODO Auto-generated method stub
			String json = new JsonBuild().setModel(mOrderEvaluate).getJson();
			return new OrderEvaluateNet(context, json);
		}

		@Override
		public void onSuccess(Object object) {
			ToastUtil.showToast(context, R.string.submit_success);
			// 已评价
			status = 2;
			layout_message.setVisibility(View.VISIBLE);
			et_message.setVisibility(View.GONE);
			hint.setVisibility(View.GONE);
			hint_line.setVisibility(View.GONE);
			et_message2.setVisibility(View.VISIBLE);
			et_message2.setText(et_message.getText().toString());
			btn_confirm.setText(R.string.agin_xiadan);
			rb_rating_b.setIsIndicator(true);
			isTouch = false;
			db_myorder.onUpdateValuate(order_id, Value.VALUATE_STATUS);
			getOrderDetail(order_id,true);
		}

		@Override
		public void onFailed(int status, String msg) {
			// TODO Auto-generated method stub
			ToastUtil.showToast(context, getResources().getString(R.string.no_network));
		}
	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (keyCode == KeyEvent.KEYCODE_BACK) {

			if (contentView.getChildCount() == 0) {
				finish();
			} else {
				contentView.onNextView();
			}

			return true;

		}
		return false;
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.iv_left:
			if (contentView.getChildCount() == 0) {
				finish();
			} else {
				contentView.onNextView();
			}
			break;
		case R.id.et_message:
			new Handler().postDelayed(new  Runnable() {
				public void run() {
					myscrollview.fullScroll(ScrollView.FOCUS_DOWN);
				}
			},800);
			break;
		default:
			super.onClick(v);
			break;
		}

	}

	private int id = -1;
	Handler mHandler = new Handler();

	@Override
	protected void onDestroy() {
		if (mOrderEvaluateTask != null
				&& mOrderEvaluateTask.getStatus() != AsyncTask.Status.FINISHED)
			mOrderEvaluateTask.cancel(true);
		if (mOrderDetailTask != null
				&& mOrderDetailTask.getStatus() != AsyncTask.Status.FINISHED)
			mOrderDetailTask.cancel(true);
		super.onDestroy();
	}

	@Override
	public void finish() {
		ArrayList<String> lits_order_id2 = new ArrayList<String>();
		lits_order_id2.add(lits_order_id.get(0));
		if (id >= 0)
			for (int i = 0; i <= id; i++) {
				lits_order_id2.add(lits_order_id.get(i + 1));
			}
		Intent intent = new Intent();
		Bundle bundle = new Bundle();
		bundle.putStringArrayList(OrderMsg.lits_order_id, lits_order_id2);
		intent.putExtras(bundle);
		setResult(resultCode, intent);
		super.finish();
	}

	@Override
	public void onNotify(int type,JSONObject jb,Msgs.Data msgs_data){
		if (!isonNotify)
			return;
		switch (type) {
		case GMsg.ONLINE_FINISH:
			String order_id = null;
			try {
				JSONObject json_jmsg = jb.getJSONObject(GMsg.msg_jmsg);
				JSONObject json_data = new JSONObject(
						json_jmsg.getString(GMsg.msg_data));
				order_id = json_data.getString(GMsg.msg_order_id);
			} catch (JSONException e1) {
			}
			if (order_id != null) {
				addCardView(order_id);
			}
			break;
		}
		super.onNotify(type, jb,msgs_data);
	}

}
